<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
  <head>
    <meta charset="utf-8" />
    <meta name="generator" content="pandoc" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=yes"
    />
    <title>introduction</title>
    <style type="text/css">
      code {
        white-space: pre-wrap;
      }
      span.smallcaps {
        font-variant: small-caps;
      }
      span.underline {
        text-decoration: underline;
      }
      div.column {
        display: inline-block;
        vertical-align: top;
        width: 50%;
      }
    </style>
  </head>
  <body>
    <h3 id="navigation">Navigation</h3>
    <ul>
      <li>
        <a href="https://docs.python.org/3/genindex.html" title="General Index"
          >index</a
        >
      </li>
      <li>
        <a
          href="https://docs.python.org/3/py-modindex.html"
          title="Python Module Index"
          >modules</a
        >
        |
      </li>
      <li>
        <a href="controlflow.html" title="4. More Control Flow Tools">next</a> |
      </li>
      <li>
        <a href="interpreter.html" title="2. Using the Python Interpreter"
          >previous</a
        >
        |
      </li>
      <li><img src="../_static/py.png" /></li>
      <li><a href="https://www.python.org/">Python</a> »</li>
      <li>
        <a href="https://docs.python.org/3/index.html">3.9.5 Documentation</a> »
      </li>
      <li><a href="index.html">The Python Tutorial</a> »</li>
      <li><div class="line-block"></div></li>
    </ul>
    <p><span id="tut-informal"></span></p>
    <h1 id="an-informal-introduction-to-python">
      <span class="section-number">3. </span>An Informal Introduction to
      Python<a
        href="#an-informal-introduction-to-python"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h1>
    <p>
      In the following examples, input and output are distinguished by the
      presence or absence of prompts (<a
        href="https://docs.python.org/3/glossary.html#term-0"
        class="reference internal"
        ><span class="xref std std-term">&gt;&gt;&gt;</span></a
      >
      and
      <a
        href="https://docs.python.org/3/glossary.html#term-1"
        class="reference internal"
        ><span class="xref std std-term">…</span></a
      >): to repeat the example, you must type everything after the prompt, when
      the prompt appears; lines that do not begin with a prompt are output from
      the interpreter. Note that a secondary prompt on a line by itself in an
      example means you must type a blank line; this is used to end a multi-line
      command.
    </p>
    <p>
      Many of the examples in this manual, even those entered at the interactive
      prompt, include comments. Comments in Python start with the hash
      character, <code>#</code>, and extend to the end of the physical line. A
      comment may appear at the start of a line or following whitespace or code,
      but not within a string literal. A hash character within a string literal
      is just a hash character. Since comments are to clarify code and are not
      interpreted by Python, they may be omitted when typing in examples.
    </p>
    <p>Some examples:</p>
    <pre><code># this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = &quot;# This is not a comment because it&#39;s inside quotes.&quot;</code></pre>
    <p><span id="tut-calculator"></span></p>
    <h2 id="using-python-as-a-calculator">
      <span class="section-number">3.1. </span>Using Python as a Calculator<a
        href="#using-python-as-a-calculator"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h2>
    <p>
      Let’s try some simple Python commands. Start the interpreter and wait for
      the primary prompt, <code>&gt;&gt;&gt;</code>. (It shouldn’t take long.)
    </p>
    <p><span id="tut-numbers"></span></p>
    <h3 id="numbers">
      <span class="section-number">3.1.1. </span>Numbers<a
        href="#numbers"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>
      The interpreter acts as a simple calculator: you can type an expression at
      it and it will write the value. Expression syntax is straightforward: the
      operators <code>+</code>, <code>-</code>, <code>*</code> and
      <code>/</code> work just like in most other languages (for example, Pascal
      or C); parentheses (<code>()</code>) can be used for grouping. For
      example:
    </p>
    <pre><code>&gt;&gt;&gt; 2 + 2
4
&gt;&gt;&gt; 50 - 5*6
20
&gt;&gt;&gt; (50 - 5*6) / 4
5.0
&gt;&gt;&gt; 8 / 5  # division always returns a floating point number
1.6</code></pre>
    <p>
      The integer numbers (e.g. <code>2</code>, <code>4</code>, <code>20</code>)
      have type
      <a
        href="https://docs.python.org/3/library/functions.html#int"
        class="reference internal"
        title="int"
        ><code class="sourceCode python"><span class="bu">int</span></code></a
      >, the ones with a fractional part (e.g. <code>5.0</code>,
      <code>1.6</code>) have type
      <a
        href="https://docs.python.org/3/library/functions.html#float"
        class="reference internal"
        title="float"
        ><code class="sourceCode python"><span class="bu">float</span></code></a
      >. We will see more about numeric types later in the tutorial.
    </p>
    <p>
      Division (<code>/</code>) always returns a float. To do
      <a
        href="https://docs.python.org/3/glossary.html#term-floor-division"
        class="reference internal"
        ><span class="xref std std-term">floor division</span></a
      >
      and get an integer result (discarding any fractional result) you can use
      the <code>//</code> operator; to calculate the remainder you can use
      <code>%</code>:
    </p>
    <pre><code>&gt;&gt;&gt; 17 / 3  # classic division returns a float
5.666666666666667
&gt;&gt;&gt;
&gt;&gt;&gt; 17 // 3  # floor division discards the fractional part
5
&gt;&gt;&gt; 17 % 3  # the % operator returns the remainder of the division
2
&gt;&gt;&gt; 5 * 3 + 2  # floored quotient * divisor + remainder
17</code></pre>
    <p>
      With Python, it is possible to use the <code>**</code> operator to
      calculate powers
      <a href="#id3" id="id1" class="footnote-reference brackets">1</a>:
    </p>
    <pre><code>&gt;&gt;&gt; 5 ** 2  # 5 squared
25
&gt;&gt;&gt; 2 ** 7  # 2 to the power of 7
128</code></pre>
    <p>
      The equal sign (<code>=</code>) is used to assign a value to a variable.
      Afterwards, no result is displayed before the next interactive prompt:
    </p>
    <pre><code>&gt;&gt;&gt; width = 20
&gt;&gt;&gt; height = 5 * 9
&gt;&gt;&gt; width * height
900</code></pre>
    <p>
      If a variable is not “defined” (assigned a value), trying to use it will
      give you an error:
    </p>
    <pre><code>&gt;&gt;&gt; n  # try to access an undefined variable
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
NameError: name &#39;n&#39; is not defined</code></pre>
    <p>
      There is full support for floating point; operators with mixed type
      operands convert the integer operand to floating point:
    </p>
    <pre><code>&gt;&gt;&gt; 4 * 3.75 - 1
14.0</code></pre>
    <p>
      In interactive mode, the last printed expression is assigned to the
      variable <code>_</code>. This means that when you are using Python as a
      desk calculator, it is somewhat easier to continue calculations, for
      example:
    </p>
    <pre><code>&gt;&gt;&gt; tax = 12.5 / 100
&gt;&gt;&gt; price = 100.50
&gt;&gt;&gt; price * tax
12.5625
&gt;&gt;&gt; price + _
113.0625
&gt;&gt;&gt; round(_, 2)
113.06</code></pre>
    <p>
      This variable should be treated as read-only by the user. Don’t explicitly
      assign a value to it — you would create an independent local variable with
      the same name masking the built-in variable with its magic behavior.
    </p>
    <p>
      In addition to
      <a
        href="https://docs.python.org/3/library/functions.html#int"
        class="reference internal"
        title="int"
        ><code class="sourceCode python"><span class="bu">int</span></code></a
      >
      and
      <a
        href="https://docs.python.org/3/library/functions.html#float"
        class="reference internal"
        title="float"
        ><code class="sourceCode python"><span class="bu">float</span></code></a
      >, Python supports other types of numbers, such as
      <a
        href="https://docs.python.org/3/library/decimal.html#decimal.Decimal"
        class="reference internal"
        title="decimal.Decimal"
        ><code class="sourceCode python">Decimal</code></a
      >
      and
      <a
        href="https://docs.python.org/3/library/fractions.html#fractions.Fraction"
        class="reference internal"
        title="fractions.Fraction"
        ><code class="sourceCode python">Fraction</code></a
      >. Python also has built-in support for
      <a
        href="https://docs.python.org/3/library/stdtypes.html#typesnumeric"
        class="reference internal"
        ><span class="std std-ref">complex numbers</span></a
      >, and uses the <code>j</code> or <code>J</code> suffix to indicate the
      imaginary part (e.g. <code>3+5j</code>).
    </p>
    <p><span id="tut-strings"></span></p>
    <h3 id="strings">
      <span class="section-number">3.1.2. </span>Strings<a
        href="#strings"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>
      Besides numbers, Python can also manipulate strings, which can be
      expressed in several ways. They can be enclosed in single quotes
      (<code>'...'</code>) or double quotes (<code>"..."</code>) with the same
      result <a href="#id4" id="id2" class="footnote-reference brackets">2</a>.
      <code>\</code> can be used to escape quotes:
    </p>
    <pre><code>&gt;&gt;&gt; &#39;spam eggs&#39;  # single quotes
&#39;spam eggs&#39;
&gt;&gt;&gt; &#39;doesn\&#39;t&#39;  # use \&#39; to escape the single quote...
&quot;doesn&#39;t&quot;
&gt;&gt;&gt; &quot;doesn&#39;t&quot;  # ...or use double quotes instead
&quot;doesn&#39;t&quot;
&gt;&gt;&gt; &#39;&quot;Yes,&quot; they said.&#39;
&#39;&quot;Yes,&quot; they said.&#39;
&gt;&gt;&gt; &quot;\&quot;Yes,\&quot; they said.&quot;
&#39;&quot;Yes,&quot; they said.&#39;
&gt;&gt;&gt; &#39;&quot;Isn\&#39;t,&quot; they said.&#39;
&#39;&quot;Isn\&#39;t,&quot; they said.&#39;</code></pre>
    <p>
      In the interactive interpreter, the output string is enclosed in quotes
      and special characters are escaped with backslashes. While this might
      sometimes look different from the input (the enclosing quotes could
      change), the two strings are equivalent. The string is enclosed in double
      quotes if the string contains a single quote and no double quotes,
      otherwise it is enclosed in single quotes. The
      <a
        href="https://docs.python.org/3/library/functions.html#print"
        class="reference internal"
        title="print"
        ><code class="sourceCode python"
          ><span class="bu">print</span>()</code
        ></a
      >
      function produces a more readable output, by omitting the enclosing quotes
      and by printing escaped and special characters:
    </p>
    <pre><code>&gt;&gt;&gt; &#39;&quot;Isn\&#39;t,&quot; they said.&#39;
&#39;&quot;Isn\&#39;t,&quot; they said.&#39;
&gt;&gt;&gt; print(&#39;&quot;Isn\&#39;t,&quot; they said.&#39;)
&quot;Isn&#39;t,&quot; they said.
&gt;&gt;&gt; s = &#39;First line.\nSecond line.&#39;  # \n means newline
&gt;&gt;&gt; s  # without print(), \n is included in the output
&#39;First line.\nSecond line.&#39;
&gt;&gt;&gt; print(s)  # with print(), \n produces a new line
First line.
Second line.</code></pre>
    <p>
      If you don’t want characters prefaced by <code>\</code> to be interpreted
      as special characters, you can use <em>raw strings</em> by adding an
      <code>r</code> before the first quote:
    </p>
    <pre><code>&gt;&gt;&gt; print(&#39;C:\some\name&#39;)  # here \n means newline!
C:\some
ame
&gt;&gt;&gt; print(r&#39;C:\some\name&#39;)  # note the r before the quote
C:\some\name</code></pre>
    <p>
      String literals can span multiple lines. One way is using triple-quotes:
      <code>"""..."""</code> or <code>'''...'''</code>. End of lines are
      automatically included in the string, but it’s possible to prevent this by
      adding a <code>\</code> at the end of the line. The following example:
    </p>
    <pre><code>print(&quot;&quot;&quot;\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
&quot;&quot;&quot;)</code></pre>
    <p>
      produces the following output (note that the initial newline is not
      included):
    </p>
    <pre><code>Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to</code></pre>
    <p>
      Strings can be concatenated (glued together) with the
      <code>+</code> operator, and repeated with <code>*</code>:
    </p>
    <pre><code>&gt;&gt;&gt; # 3 times &#39;un&#39;, followed by &#39;ium&#39;
&gt;&gt;&gt; 3 * &#39;un&#39; + &#39;ium&#39;
&#39;unununium&#39;</code></pre>
    <p>
      Two or more <em>string literals</em> (i.e. the ones enclosed between
      quotes) next to each other are automatically concatenated.
    </p>
    <pre><code>&gt;&gt;&gt; &#39;Py&#39; &#39;thon&#39;
&#39;Python&#39;</code></pre>
    <p>
      This feature is particularly useful when you want to break long strings:
    </p>
    <pre><code>&gt;&gt;&gt; text = (&#39;Put several strings within parentheses &#39;
...         &#39;to have them joined together.&#39;)
&gt;&gt;&gt; text
&#39;Put several strings within parentheses to have them joined together.&#39;</code></pre>
    <p>
      This only works with two literals though, not with variables or
      expressions:
    </p>
    <pre><code>&gt;&gt;&gt; prefix = &#39;Py&#39;
&gt;&gt;&gt; prefix &#39;thon&#39;  # can&#39;t concatenate a variable and a string literal
  File &quot;&lt;stdin&gt;&quot;, line 1
    prefix &#39;thon&#39;
                ^
SyntaxError: invalid syntax
&gt;&gt;&gt; (&#39;un&#39; * 3) &#39;ium&#39;
  File &quot;&lt;stdin&gt;&quot;, line 1
    (&#39;un&#39; * 3) &#39;ium&#39;
                   ^
SyntaxError: invalid syntax</code></pre>
    <p>
      If you want to concatenate variables or a variable and a literal, use
      <code>+</code>:
    </p>
    <pre><code>&gt;&gt;&gt; prefix + &#39;thon&#39;
&#39;Python&#39;</code></pre>
    <p>
      Strings can be <em>indexed</em> (subscripted), with the first character
      having index 0. There is no separate character type; a character is simply
      a string of size one:
    </p>
    <pre><code>&gt;&gt;&gt; word = &#39;Python&#39;
&gt;&gt;&gt; word[0]  # character in position 0
&#39;P&#39;
&gt;&gt;&gt; word[5]  # character in position 5
&#39;n&#39;</code></pre>
    <p>
      Indices may also be negative numbers, to start counting from the right:
    </p>
    <pre><code>&gt;&gt;&gt; word[-1]  # last character
&#39;n&#39;
&gt;&gt;&gt; word[-2]  # second-last character
&#39;o&#39;
&gt;&gt;&gt; word[-6]
&#39;P&#39;</code></pre>
    <p>Note that since -0 is the same as 0, negative indices start from -1.</p>
    <p>
      In addition to indexing, <em>slicing</em> is also supported. While
      indexing is used to obtain individual characters, <em>slicing</em> allows
      you to obtain substring:
    </p>
    <pre><code>&gt;&gt;&gt; word[0:2]  # characters from position 0 (included) to 2 (excluded)
&#39;Py&#39;
&gt;&gt;&gt; word[2:5]  # characters from position 2 (included) to 5 (excluded)
&#39;tho&#39;</code></pre>
    <p>
      Note how the start is always included, and the end always excluded. This
      makes sure that <code>s[:i] + s[i:]</code> is always equal to
      <code>s</code>:
    </p>
    <pre><code>&gt;&gt;&gt; word[:2] + word[2:]
&#39;Python&#39;
&gt;&gt;&gt; word[:4] + word[4:]
&#39;Python&#39;</code></pre>
    <p>
      Slice indices have useful defaults; an omitted first index defaults to
      zero, an omitted second index defaults to the size of the string being
      sliced.
    </p>
    <pre><code>&gt;&gt;&gt; word[:2]   # character from the beginning to position 2 (excluded)
&#39;Py&#39;
&gt;&gt;&gt; word[4:]   # characters from position 4 (included) to the end
&#39;on&#39;
&gt;&gt;&gt; word[-2:]  # characters from the second-last (included) to the end
&#39;on&#39;</code></pre>
    <p>
      One way to remember how slices work is to think of the indices as pointing
      <em>between</em> characters, with the left edge of the first character
      numbered 0. Then the right edge of the last character of a string of
      <em>n</em> characters has index <em>n</em>, for example:
    </p>
    <pre><code> +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1</code></pre>
    <p>
      The first row of numbers gives the position of the indices 0…6 in the
      string; the second row gives the corresponding negative indices. The slice
      from <em>i</em> to <em>j</em> consists of all characters between the edges
      labeled <em>i</em> and <em>j</em>, respectively.
    </p>
    <p>
      For non-negative indices, the length of a slice is the difference of the
      indices, if both are within bounds. For example, the length of
      <code>word[1:3]</code> is 2.
    </p>
    <p>Attempting to use an index that is too large will result in an error:</p>
    <pre><code>&gt;&gt;&gt; word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
IndexError: string index out of range</code></pre>
    <p>
      However, out of range slice indexes are handled gracefully when used for
      slicing:
    </p>
    <pre><code>&gt;&gt;&gt; word[4:42]
&#39;on&#39;
&gt;&gt;&gt; word[42:]
&#39;&#39;</code></pre>
    <p>
      Python strings cannot be changed — they are
      <a
        href="https://docs.python.org/3/glossary.html#term-immutable"
        class="reference internal"
        ><span class="xref std std-term">immutable</span></a
      >. Therefore, assigning to an indexed position in the string results in an
      error:
    </p>
    <pre><code>&gt;&gt;&gt; word[0] = &#39;J&#39;
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
TypeError: &#39;str&#39; object does not support item assignment
&gt;&gt;&gt; word[2:] = &#39;py&#39;
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
TypeError: &#39;str&#39; object does not support item assignment</code></pre>
    <p>If you need a different string, you should create a new one:</p>
    <pre><code>&gt;&gt;&gt; &#39;J&#39; + word[1:]
&#39;Jython&#39;
&gt;&gt;&gt; word[:2] + &#39;py&#39;
&#39;Pypy&#39;</code></pre>
    <p>
      The built-in function
      <a
        href="https://docs.python.org/3/library/functions.html#len"
        class="reference internal"
        title="len"
        ><code class="sourceCode python"><span class="bu">len</span>()</code></a
      >
      returns the length of a string:
    </p>
    <pre><code>&gt;&gt;&gt; s = &#39;supercalifragilisticexpialidocious&#39;
&gt;&gt;&gt; len(s)
34</code></pre>
    <p>See also</p>
    <p>
      <a
        href="https://docs.python.org/3/library/stdtypes.html#textseq"
        class="reference internal"
        ><span class="std std-ref">Text Sequence Type — str</span></a
      ><br />
      Strings are examples of <em>sequence types</em>, and support the common
      operations supported by such types.
    </p>
    <p>
      <a
        href="https://docs.python.org/3/library/stdtypes.html#string-methods"
        class="reference internal"
        ><span class="std std-ref">String Methods</span></a
      ><br />
      Strings support a large number of methods for basic transformations and
      searching.
    </p>
    <p>
      <a
        href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings"
        class="reference internal"
        ><span class="std std-ref">Formatted string literals</span></a
      ><br />
      String literals that have embedded expressions.
    </p>
    <p>
      <a
        href="https://docs.python.org/3/library/string.html#formatstrings"
        class="reference internal"
        ><span class="std std-ref">Format String Syntax</span></a
      ><br />
      Information about string formatting with
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.format"
        class="reference internal"
        title="str.format"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.<span class="bu">format</span>()</code
        ></a
      >.
    </p>
    <p>
      <a
        href="https://docs.python.org/3/library/stdtypes.html#old-string-formatting"
        class="reference internal"
        ><span class="std std-ref">printf-style String Formatting</span></a
      ><br />
      The old formatting operations invoked when strings are the left operand of
      the <code>%</code> operator are described in more detail here.
    </p>
    <p><span id="tut-lists"></span></p>
    <h3 id="lists">
      <span class="section-number">3.1.3. </span>Lists<a
        href="#lists"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>
      Python knows a number of <em>compound</em> data types, used to group
      together other values. The most versatile is the <em>list</em>, which can
      be written as a list of comma-separated values (items) between square
      brackets. Lists might contain items of different types, but usually the
      items all have the same type.
    </p>
    <pre><code>&gt;&gt;&gt; squares = [1, 4, 9, 16, 25]
&gt;&gt;&gt; squares
[1, 4, 9, 16, 25]</code></pre>
    <p>
      Like strings (and all other built-in
      <a
        href="https://docs.python.org/3/glossary.html#term-sequence"
        class="reference internal"
        ><span class="xref std std-term">sequence</span></a
      >
      types), lists can be indexed and sliced:
    </p>
    <pre><code>&gt;&gt;&gt; squares[0]  # indexing returns the item
1
&gt;&gt;&gt; squares[-1]
25
&gt;&gt;&gt; squares[-3:]  # slicing returns a new list
[9, 16, 25]</code></pre>
    <p>
      All slice operations return a new list containing the requested elements.
      This means that the following slice returns a
      <a
        href="https://docs.python.org/3/library/copy.html#shallow-vs-deep-copy"
        class="reference internal"
        ><span class="std std-ref">shallow copy</span></a
      >
      of the list:
    </p>
    <pre><code>&gt;&gt;&gt; squares[:]
[1, 4, 9, 16, 25]</code></pre>
    <p>Lists also support operations like concatenation:</p>
    <pre><code>&gt;&gt;&gt; squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</code></pre>
    <p>
      Unlike strings, which are
      <a
        href="https://docs.python.org/3/glossary.html#term-immutable"
        class="reference internal"
        ><span class="xref std std-term">immutable</span></a
      >, lists are a
      <a
        href="https://docs.python.org/3/glossary.html#term-mutable"
        class="reference internal"
        ><span class="xref std std-term">mutable</span></a
      >
      type, i.e. it is possible to change their content:
    </p>
    <pre><code>&gt;&gt;&gt; cubes = [1, 8, 27, 65, 125]  # something&#39;s wrong here
&gt;&gt;&gt; 4 ** 3  # the cube of 4 is 64, not 65!
64
&gt;&gt;&gt; cubes[3] = 64  # replace the wrong value
&gt;&gt;&gt; cubes
[1, 8, 27, 64, 125]</code></pre>
    <p>
      You can also add new items at the end of the list, by using the
      <code>append()</code> <em>method</em> (we will see more about methods
      later):
    </p>
    <pre><code>&gt;&gt;&gt; cubes.append(216)  # add the cube of 6
&gt;&gt;&gt; cubes.append(7 ** 3)  # and the cube of 7
&gt;&gt;&gt; cubes
[1, 8, 27, 64, 125, 216, 343]</code></pre>
    <p>
      Assignment to slices is also possible, and this can even change the size
      of the list or clear it entirely:
    </p>
    <pre><code>&gt;&gt;&gt; letters = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]
&gt;&gt;&gt; letters
[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]
&gt;&gt;&gt; # replace some values
&gt;&gt;&gt; letters[2:5] = [&#39;C&#39;, &#39;D&#39;, &#39;E&#39;]
&gt;&gt;&gt; letters
[&#39;a&#39;, &#39;b&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;f&#39;, &#39;g&#39;]
&gt;&gt;&gt; # now remove them
&gt;&gt;&gt; letters[2:5] = []
&gt;&gt;&gt; letters
[&#39;a&#39;, &#39;b&#39;, &#39;f&#39;, &#39;g&#39;]
&gt;&gt;&gt; # clear the list by replacing all the elements with an empty list
&gt;&gt;&gt; letters[:] = []
&gt;&gt;&gt; letters
[]</code></pre>
    <p>
      The built-in function
      <a
        href="https://docs.python.org/3/library/functions.html#len"
        class="reference internal"
        title="len"
        ><code class="sourceCode python"><span class="bu">len</span>()</code></a
      >
      also applies to lists:
    </p>
    <pre><code>&gt;&gt;&gt; letters = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]
&gt;&gt;&gt; len(letters)
4</code></pre>
    <p>
      It is possible to nest lists (create lists containing other lists), for
      example:
    </p>
    <pre><code>&gt;&gt;&gt; a = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
&gt;&gt;&gt; n = [1, 2, 3]
&gt;&gt;&gt; x = [a, n]
&gt;&gt;&gt; x
[[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;], [1, 2, 3]]
&gt;&gt;&gt; x[0]
[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
&gt;&gt;&gt; x[0][1]
&#39;b&#39;</code></pre>
    <p><span id="tut-firststeps"></span></p>
    <h2 id="first-steps-towards-programming">
      <span class="section-number">3.2. </span>First Steps Towards Programming<a
        href="#first-steps-towards-programming"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h2>
    <p>
      Of course, we can use Python for more complicated tasks than adding two
      and two together. For instance, we can write an initial sub-sequence of
      the
      <a
        href="https://en.wikipedia.org/wiki/Fibonacci_number"
        class="reference external"
        >Fibonacci series</a
      >
      as follows:
    </p>
    <pre><code>&gt;&gt;&gt; # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
&gt;&gt;&gt; while a &lt; 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8</code></pre>
    <p>This example introduces several new features.</p>
    <ul>
      <li>
        <p>
          The first line contains a <em>multiple assignment</em>: the variables
          <code>a</code> and <code>b</code> simultaneously get the new values 0
          and 1. On the last line this is used again, demonstrating that the
          expressions on the right-hand side are all evaluated first before any
          of the assignments take place. The right-hand side expressions are
          evaluated from the left to the right.
        </p>
      </li>
      <li>
        <p>
          The
          <a
            href="https://docs.python.org/3/reference/compound_stmts.html#while"
            class="reference internal"
            ><code class="xref std std-keyword docutils literal notranslate"
              >while</code
            ></a
          >
          loop executes as long as the condition (here: <code>a &lt; 10</code>)
          remains true. In Python, like in C, any non-zero integer value is
          true; zero is false. The condition may also be a string or list value,
          in fact any sequence; anything with a non-zero length is true, empty
          sequences are false. The test used in the example is a simple
          comparison. The standard comparison operators are written the same as
          in C: <code>&lt;</code> (less than), <code>&gt;</code> (greater than),
          <code>==</code> (equal to), <code>&lt;=</code> (less than or equal
          to), <code>&gt;=</code> (greater than or equal to) and
          <code>!=</code> (not equal to).
        </p>
      </li>
      <li>
        <p>
          The <em>body</em> of the loop is <em>indented</em>: indentation is
          Python’s way of grouping statements. At the interactive prompt, you
          have to type a tab or space(s) for each indented line. In practice you
          will prepare more complicated input for Python with a text editor; all
          decent text editors have an auto-indent facility. When a compound
          statement is entered interactively, it must be followed by a blank
          line to indicate completion (since the parser cannot guess when you
          have typed the last line). Note that each line within a basic block
          must be indented by the same amount.
        </p>
      </li>
      <li>
        <p>
          The
          <a
            href="https://docs.python.org/3/library/functions.html#print"
            class="reference internal"
            title="print"
            ><code class="sourceCode python"
              ><span class="bu">print</span>()</code
            ></a
          >
          function writes the value of the argument(s) it is given. It differs
          from just writing the expression you want to write (as we did earlier
          in the calculator examples) in the way it handles multiple arguments,
          floating point quantities, and strings. Strings are printed without
          quotes, and a space is inserted between items, so you can format
          things nicely, like this:
        </p>
        <pre><code>&gt;&gt;&gt; i = 256*256
&gt;&gt;&gt; print(&#39;The value of i is&#39;, i)
The value of i is 65536</code></pre>
        <p>
          The keyword argument <em>end</em> can be used to avoid the newline
          after the output, or end the output with a different string:
        </p>
        <pre><code>&gt;&gt;&gt; a, b = 0, 1
&gt;&gt;&gt; while a &lt; 1000:
...     print(a, end=&#39;,&#39;)
...     a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,</code></pre>
      </li>
    </ul>
    <p>Footnotes</p>
    <p>
      <span class="brackets"><a href="#id1" class="fn-backref">1</a></span
      ><br />
      Since <code>**</code> has higher precedence than <code>-</code>,
      <code>-3**2</code> will be interpreted as <code>-(3**2)</code> and thus
      result in <code>-9</code>. To avoid this and get <code>9</code>, you can
      use <code>(-3)**2</code>.
    </p>
    <p>
      <span class="brackets"><a href="#id2" class="fn-backref">2</a></span
      ><br />
      Unlike other languages, special characters such as <code>\n</code> have
      the same meaning with both single (<code>'...'</code>) and double
      (<code>"..."</code>) quotes. The only difference between the two is that
      within single quotes you don’t need to escape <code>"</code> (but you have
      to escape <code>\'</code>) and vice versa.
    </p>
    <h3 id="table-of-contents">
      <a href="https://docs.python.org/3/contents.html">Table of Contents</a>
    </h3>
    <ul>
      <li>
        <a href="#" class="reference internal"
          >3. An Informal Introduction to Python</a
        >
        <ul>
          <li>
            <a href="#using-python-as-a-calculator" class="reference internal"
              >3.1. Using Python as a Calculator</a
            >
            <ul>
              <li>
                <a href="#numbers" class="reference internal">3.1.1. Numbers</a>
              </li>
              <li>
                <a href="#strings" class="reference internal">3.1.2. Strings</a>
              </li>
              <li>
                <a href="#lists" class="reference internal">3.1.3. Lists</a>
              </li>
            </ul>
          </li>
          <li>
            <a
              href="#first-steps-towards-programming"
              class="reference internal"
              >3.2. First Steps Towards Programming</a
            >
          </li>
        </ul>
      </li>
    </ul>
    <h4 id="previous-topic">Previous topic</h4>
    <p>
      <a href="interpreter.html" title="previous chapter"
        ><span class="section-number">2. </span>Using the Python Interpreter</a
      >
    </p>
    <h4 id="next-topic">Next topic</h4>
    <p>
      <a href="controlflow.html" title="next chapter"
        ><span class="section-number">4. </span>More Control Flow Tools</a
      >
    </p>
    <h3 id="this-page">This Page</h3>
    <ul>
      <li><a href="https://docs.python.org/3/bugs.html">Report a Bug</a></li>
      <li>
        <a
          href="https://github.com/python/cpython/blob/3.9/Doc/tutorial/introduction.rst"
          >Show Source</a
        >
      </li>
    </ul>
    <h3 id="navigation-1">Navigation</h3>
    <ul>
      <li>
        <a href="https://docs.python.org/3/genindex.html" title="General Index"
          >index</a
        >
      </li>
      <li>
        <a
          href="https://docs.python.org/3/py-modindex.html"
          title="Python Module Index"
          >modules</a
        >
        |
      </li>
      <li>
        <a href="controlflow.html" title="4. More Control Flow Tools">next</a> |
      </li>
      <li>
        <a href="interpreter.html" title="2. Using the Python Interpreter"
          >previous</a
        >
        |
      </li>
      <li><img src="../_static/py.png" /></li>
      <li><a href="https://www.python.org/">Python</a> »</li>
      <li>
        <a href="https://docs.python.org/3/index.html">3.9.5 Documentation</a> »
      </li>
      <li><a href="index.html">The Python Tutorial</a> »</li>
      <li><div class="line-block"></div></li>
    </ul>
    <p>
      ©
      <a href="https://docs.python.org/3/copyright.html">Copyright</a>
      2001-2021, Python Software Foundation.<br />
      The Python Software Foundation is a non-profit corporation.
      <a href="https://www.python.org/psf/donations/">Please donate.</a>
    </p>
    <p>
      Last updated on May 30, 2021.
      <a href="https://docs.python.org/3/bugs.html">Found a bug</a>?<br />
      Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 2.4.4.
    </p>
  </body>
</html>
